package com.yx.front.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yx.front.config.global.BizException;
import com.yx.front.config.global.CommonResult;
import com.yx.front.converter.SysUserConverter;
import com.yx.front.enums.IntBoolean;
import com.yx.front.enums.Sex;
import com.yx.front.model.SysUser;
import com.yx.front.model.base.BaseParam;
import com.yx.front.model.param.SysUserParam;
import com.yx.front.model.vo.AdviceFriendVo;
import com.yx.front.model.vo.FriendRelationVo;
import com.yx.front.model.vo.SysUserVo;
import com.yx.front.service.SysUserService;
import com.yx.front.utils.JwtUtil;
import com.yx.front.utils.LoginUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author YangXiong
 */
@Component
@Slf4j
public class SysUserManager {
    @Resource
    private DictManager dictManager;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private LoginUtil loginUtil;
    @Resource
    private SysUserConverter sysUserConverter;
    @Resource
    private FriendRelationManager friendRelationManager;

    public CommonResult<SysUserVo> getUserByName(String name) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUserName, name);
        queryWrapper.eq(SysUser::getIsManager, IntBoolean.NO.getKey());
        SysUser one = sysUserService.getOne(queryWrapper);
        if (Objects.isNull(one)) {
            throw new BizException("当前用户不存在");
        }
        SysUserVo result = sysUserConverter.sysUserToVo(one);
        return CommonResult.success(result);
    }

    public CommonResult<List<AdviceFriendVo>> getFriendList(BaseParam param) {
        //TODO 没有好友先轮询用户表，后面再考虑共同好友推荐
        List<FriendRelationVo> data = friendRelationManager.getFriends().getData();
        log.info("List<SysUserVo>>====>{}", data);
        Map<Long, FriendRelationVo> collect = data.stream().collect(Collectors.toMap(FriendRelationVo::getId, Function.identity()));
        Set<Long> ids = collect.keySet();
        Long id = loginUtil.getCurrentUser().getId();
        ArrayList<Long> userIds = new ArrayList<>(ids);
        userIds.add(id);
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.notIn(CollectionUtil.isNotEmpty(userIds), SysUser::getId, userIds);
        wrapper.eq(SysUser::getIsManager, IntBoolean.NO.getKey());
        Page<SysUser> page = new Page<>(param.getCurrentPage(), param.getTotalPage());
        Page<SysUser> userPage = sysUserService.page(page, wrapper);
        List<AdviceFriendVo> result = handlerAdviceVo(userPage.getRecords());
        return CommonResult.success(result, userPage.getTotal());
    }

    private List<AdviceFriendVo> handlerAdviceVo(List<SysUser> records) {
        List<AdviceFriendVo> vos = new ArrayList<>();
        records.forEach(one -> {
            AdviceFriendVo vo = new AdviceFriendVo();
            vo.setId(one.getId());
            vo.setUserName(one.getUserName());
            vo.setAvatar(one.getAvatar());
            vos.add(vo);
        });
        return vos;
    }

    public CommonResult<Map<String,String>> updateUser(SysUserParam user) {
        log.info("===>Param={}", user);
        SysUser sysUser = getUser(user);
        log.info("User={}", sysUser);
        boolean update = sysUserService.updateById(sysUser);
        if (update) {
            //拿到最新信息
            SysUser user1 = sysUserService.getById(user.getId());
            //更新缓存
            redisTemplate.delete("login:"+user1.getId());
            Map<String, String> map = new HashMap<>(2);
            map.put("message", "编辑成功");
            String token = JwtUtil.createJwt(user1.getId().toString());
            map.put("token", token);
            map.put("userName", user1.getUserName());
            map.put("avatar", user1.getAvatar());
            return CommonResult.success(map);
        }
        return CommonResult.fail("编辑失败");
    }

    private SysUser getUser(SysUserParam user) {
        SysUser sysUser = new SysUser();
        sysUser.setId(user.getId());
        sysUser.setAvatar(user.getAvatar());
        sysUser.setUserName(user.getUserName());
        sysUser.setPhone(user.getPhone());
        sysUser.setAccount(user.getAccount());
        sysUser.setSex(Sex.getKeyByValue(user.getSex()));
        sysUser.setBirthday(DateUtil.parse(user.getBirthday()));
        sysUser.setEmail(user.getEmail());
        sysUser.setHobby(dictManager.getKeyByValue(user.getHobby()));
        return sysUser;
    }
}
